<script setup>
import { useThemeStore } from '@/stores/theme'
import { computed, ref } from 'vue'
import MarkdownIt from 'markdown-it'
import { textToSpeech } from '@/api/voice'
import { ElMessage } from 'element-plus'
import { VideoPlay, VideoPause } from '@element-plus/icons-vue'

// 初始化markdown解析器
const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true
})

// 主题状态
const themeStore = useThemeStore()

// 接收父组件传递的属性
const props = defineProps({
  message: {
    type: Object,
    required: true
  }
})

// 语音播放状态
const isPlayingAudio = ref(false)
const currentAudio = ref(null)

// 处理AI消息内容，将markdown转换为HTML
const formattedContent = computed(() => {
  if (props.message.type === 'user') {
    return props.message.content
  } else {
    return md.render(props.message.content || '')
  }
})

// 播放消息语音
const playMessageAudio = async () => {
  try {
    if (isPlayingAudio.value) {
      ElMessage.warning('正在播放语音，请稍候...')
      return
    }

    isPlayingAudio.value = true
    ElMessage.info('正在生成语音...')

    const response = await textToSpeech(props.message.content)
    playAudioFromBlob(response)

  } catch (error) {
    console.error('语音播放失败:', error)
    ElMessage.error('语音播放失败: ' + error.message)
  } finally {
    isPlayingAudio.value = false
  }
}

// 停止播放
const stopAudio = () => {
  if (currentAudio.value) {
    currentAudio.value.pause()
    currentAudio.value.currentTime = 0
    currentAudio.value = null
    isPlayingAudio.value = false
  }
}

// 从Blob播放音频
const playAudioFromBlob = (audioBlob) => {
  try {
    const audioUrl = URL.createObjectURL(audioBlob)
    const audio = new Audio(audioUrl)

    audio.onended = () => {
      URL.revokeObjectURL(audioUrl)
      isPlayingAudio.value = false
      currentAudio.value = null
    }

    audio.onerror = () => {
      URL.revokeObjectURL(audioUrl)
      isPlayingAudio.value = false
      currentAudio.value = null
      ElMessage.error('音频播放失败')
    }

    currentAudio.value = audio
    audio.play()

  } catch (error) {
    console.error('音频播放失败:', error)
    ElMessage.error('音频播放失败')
    isPlayingAudio.value = false
    currentAudio.value = null
  }
}
</script>

<template>
  <div class="message-wrapper" :class="message.type">
    <div class="message" :class="[message.type, { 'dark-mode': themeStore.isDark }]">
      <div class="message-content" v-if="message.type === 'user'">
        {{ message.content }}
      </div>
      <div class="message-content message-ai markdown-body" v-else>
        <div v-html="formattedContent"></div>
        <!-- 语音播放按钮 (只为AI消息显示) -->
        <div v-if="!message.loading" class="message-actions">
          <el-button
            type="text"
            size="small"
            @click="isPlayingAudio ? stopAudio() : playMessageAudio()"
            class="voice-play-btn"
            :disabled="isPlayingAudio && !currentAudio"
            :title="isPlayingAudio ? '停止播放' : '播放语音'"
          >
            <el-icon>
              <VideoPause v-if="isPlayingAudio" />
              <VideoPlay v-else />
            </el-icon>
            {{ isPlayingAudio ? '停止' : '播放' }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style>
/* Markdown样式 */
.markdown-body {
  line-height: 1.6;
}

.markdown-body h1, 
.markdown-body h2, 
.markdown-body h3, 
.markdown-body h4, 
.markdown-body h5, 
.markdown-body h6 {
  margin-top: 16px;
  margin-bottom: 16px;
  font-weight: 600;
}

.markdown-body h1 { font-size: 2em; }
.markdown-body h2 { font-size: 1.5em; }
.markdown-body h3 { font-size: 1.25em; }
.markdown-body h4 { font-size: 1em; }

.markdown-body ul, 
.markdown-body ol {
  padding-left: 2em;
  margin-top: 8px;
  margin-bottom: 8px;
}

.markdown-body li {
  margin-bottom: 4px;
}

.markdown-body p {
  margin-top: 8px;
  margin-bottom: 8px;
}

.markdown-body code {
  padding: 0.2em 0.4em;
  background-color: rgba(175, 184, 193, 0.2);
  border-radius: 6px;
  font-family: monospace;
}

.markdown-body pre {
  padding: 16px;
  overflow: auto;
  background-color: rgba(175, 184, 193, 0.2);
  border-radius: 6px;
  margin-top: 8px;
  margin-bottom: 8px;
}

.markdown-body blockquote {
  padding: 0 1em;
  border-left: 0.25em solid var(--el-border-color);
  margin: 8px 0;
  color: var(--el-text-color-secondary);
}
</style>

<style scoped>
.message-wrapper {
  width: 100%;
  display: flex;
  margin-bottom: 16px;
}

.message-wrapper.user {
  justify-content: flex-end;
}

.message-wrapper.ai {
  justify-content: flex-start;
}

.message {
  max-width: 80%;
  border-radius: 8px;
  overflow: hidden;
}

.message-content {
  padding: 12px 16px;
  border-radius: 8px;
  background-color: var(--el-fill-color-light);
  color: var(--el-text-color-primary);
  white-space: pre-wrap;
  word-break: break-word;
}

.message-ai {
  max-width: 100%;
  overflow-wrap: break-word;
}

.message.user .message-content {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary-dark-2);
}

.message.dark-mode.user .message-content {
  background-color: var(--el-color-primary-dark-2);
  color: var(--el-color-white);
}

.message.dark-mode .message-content {
  background-color: var(--el-fill-color-dark);
}

/* 语音播放按钮样式 */
.message-actions {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.message:hover .message-actions {
  opacity: 1;
}

.voice-play-btn {
  padding: 4px 8px;
  font-size: 12px;
  color: #8e8e93;
  transition: color 0.2s ease;
  border-radius: 4px;
}

.voice-play-btn:hover {
  color: #007AFF;
  background-color: rgba(0, 122, 255, 0.1);
}

.voice-play-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
}
</style>